<?php
/**
 * Created by PhpStorm.
 * User: vanity
 * Date: 2018/1/2
 * Time: 14:39
 */
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller
{
    public function index()
    {
        if(!empty($_SESSION['error'])){
            $this->assign('error',$_SESSION['error']);
            session('error',null);
        }
        if(!empty($_SESSION['msg'])){
            $this->assign('msg',$_SESSION['msg']);
            session('msg',null);
        }
        $this->display();
    }
    public function toLogin()
    {
        if(!IS_POST){
            $this->withError('错误操作！',$_POST,'/Admin/Login/index');
        }
        $map = array();
        $map['name'] = trim($_REQUEST['name']);
        $pwd = M('user')->where($map)->getField('password');
        if(!$pwd){
            $this->withError('用户名不存在',$_POST,'/Admin/Login/index');
        }
        if($pwd != md5($_REQUEST['password'])){
            $this->withError('密码错误',$_POST,'/Admin/Login/index');
        }
        $map['password'] = md5($_REQUEST['password']);
        $res = M('user')->field('id,name,image')->where($map)->find();
        if(empty($res)){
            $this->withError('用户名或密码错误',$_POST,'/Admin/Login/index');
        }
        session('admin',$res);
        $this->redirect('/Admin/Index/index');
    }
    public function logout()
    {
        session('admin',null);
        $this->redirect('/Admin/Login/index');
    }
    public function withError($error,$msg,$url)
    {
        session('error',$error);
        session('msg',$msg);
        $this->redirect($url);
    }
}